<template>
	<div>
		<el-row :gutter="20">
			<el-col :span="6" v-for="item in roleList" :key="item.role_id">
				<el-card
					class="cart-name"
					@mouseover.native="hoverId = item.role_id"
					@mouseleave.native="hoverId = 0"
				>
					<span>
						{{ item.role_name }}
					</span>
					<div class="mask" v-show="hoverId === item.role_id">
						<el-button
							icon="el-icon-edit-outline"
							type="text"
							@click="beginUpdate(item)"
							>编辑</el-button
						>
						<el-button
							icon="el-icon-edit-setting"
							type="text"
							@click="beginRoleFuncConfig(item.role_id)"
							>功能分配</el-button
						>
						<el-button
							icon="el-icon-delete"
							type="text"
							@click="remove(item.role_id)"
							>删除</el-button
						>
					</div>
				</el-card>
			</el-col>
			<el-col :span="6">
				<el-card class="cart-plus">
					<i class="el-icon-plus" @click="beginAdd"></i>
				</el-card>
			</el-col>
		</el-row>
		<el-dialog
			:title="`角色管理-${editor.isMode ? '新增' : '修改'}`"
			:visible.sync="editor.idEtidor"
			:modal="false"
		>
			<el-form
				label-width="80px"
				:model="editor.mode"
				:rules="editor.rules"
				ref="ruleForm"
			>
				<el-form-item label="角色名称" prop="role_name">
					<el-input v-model.trim="editor.mode.role_name"> </el-input>
				</el-form-item>
			</el-form>
			<template slot="footer">
				<el-button type="primary" @click="saveInfo">保存</el-button>
				<el-button @click="editor.idEtidor = false">取消</el-button>
			</template>
		</el-dialog>
		<el-drawer
			class="custom-drawer"
			:visible.sync="configFunc.isEdit"
			:modal="false"
			size="500px"
		>
			<h3 slot="title">角色功能分配</h3>
			<div class="tree-wrapper">
				<el-tree
					:data="configFunc.treeData"
					class="custom-tree"
					:default-expand-all="true"
					:expand-on-click-node="false"
				>
					<span
						class="custom-tree-node"
						:class="{ active: data.selected }"
						slot-scope="{ node, data }"
					>
						<span>
							<i
								v-if="data.func_key"
								class="el-icon-menu"
								style="color:rgb(64,158,255);margin-right:10px"
							></i>
							<span>{{ data.func_name }}</span>
						</span>
						<span>
							<el-switch
								class="switch-wrapper"
								:class="{ parent: data.func_key === '' }"
								v-model="data.selected"
								@change="switchChangeHandler(data)"
							>
							</el-switch>
						</span>
					</span>
				</el-tree>
				<div class="btn-wraper">
					<el-button type="primary" plain @click.native="configRoleFunc"
						>确定</el-button
					>
					<el-button @click="configFunc.isEdit = false">取消</el-button>
				</div>
			</div>
		</el-drawer>
		<!-- <div class="block"><el-avatar :size="50" :src="avatar"></el-avatar></div> -->
	</div>
</template>

<script>
import avatar from "@/views/User/avatar.jpg";
/* 
              一个组件映射一个子仓库
  通过使用 createNamespacedHelpers 创建基于某个命名空间辅助函数。
它返回一个对象，对象里有新的绑定在给定命名空间值上的组件绑定辅助函数
*/
/* import { createNamespacedHelpers } from "vuex";
// role 为子仓库 名字
const { mapState, mapActions } = createNamespacedHelpers("role"); */

//        一个组件映射多个仓库

import { mapState, mapActions } from "vuex";

import { RoleFuncApi } from "@/util/api.js";

export default {
	name: "Role",
	data() {
		return {
			avatar: avatar,
			hoverId: 0,
			configFunc: {
				isEdit: false,
				roleFuncIds: [],
				treeData: [],
				model: {
					role_id: 0,
					role_func_ids: "",
				},
			},
			editor: {
				idEtidor: false,
				isMode: true,
				mode: {
					role_id: 0,
					role_name: "学生",
				},
				rules: {
					role_name: [
						//自定义验证
						{
							validator: (rule, value, callback) => {
								if (value === "") callback(new Error("请输入角色名字"));
								else if (value.length < 2 || value.length > 10)
									callback(new Error("只能输入2-10位字符"));
								else if (
									this.roleList.some(
										(item) =>
											item.role_id != this.editor.mode.role_id &&
											item.role_name === value
									)
								)
									callback(new Error("角色名称重复"));
								else callback();
							},
							trigger: "blur",
						},
					],
				},
			},
		};
	},
	methods: {
		// ...mapActions(["init", "add", "update"]),
		// role表示子仓库
		...mapActions("role", {
			roleInit: "init",
			roleAdd: "add",
			roleUpdate: "update",
			roleRemove: "remove",
		}),
		// 命名式获取actions里的方法
		// ...mapActions({ remove2: "remove" }),
		...mapActions("func", { funcInit: "init" }),
		saveInfo() {
			this.$refs.ruleForm
				.validate()
				.then(async (res) => {
					// 新增
					if (this.editor.isMode) {
						// this.editor.mode.role_id = await this.$http({
						//   url: "/role/add",
						//   method: "post",
						//   data: {
						//     role_name: this.editor.mode.role_name,
						//   },
						// });
						// this.list.push(JSON.parse(JSON.stringify(this.editor.mode)));
						await this.roleAdd(JSON.parse(JSON.stringify(this.editor.mode)));
						this.$message({
							message: "新增成功",
							type: "success",
						});
					} else {
						// 编辑状态

						// await this.$http({
						//   url: "/role/update",
						//   method: "post",
						//   data: this.editor.mode,
						// });
						// this.list.splice(
						//   this.list.findIndex(
						//     (item) => item.role_id === this.editor.mode.role_id
						//   ),
						//   1,
						//   JSON.parse(JSON.stringify(this.editor.mode))
						// );
						await this.roleUpdate(JSON.parse(JSON.stringify(this.editor.mode)));
						this.$message({
							message: "修改成功",
							type: "success",
						});
					}
					this.editor.idEtidor = false;
				})
				.catch((err) => {
					console.log("校验失败");
				});
		},
		beginAdd() {
			this.editor.mode.role_id = 0;
			this.editor.mode.role_name = "";
			this.editor.isMode = true;
			this.editor.idEtidor = true;
			if (this.$refs.ruleForm) {
				this.$refs.ruleForm.resetFields();
			}
		},
		beginUpdate(mode) {
			this.editor.mode.role_id = mode.role_id;
			this.editor.mode.role_name = mode.role_name;
			this.editor.isMode = false;
			this.editor.idEtidor = true;
			if (this.$refs.ruleForm) {
				this.$refs.ruleForm.resetFields();
			}
		},
		remove(id) {
			this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			})
				.then(async () => {
					// console.log(id);
					// this.list.splice(
					//   this.list.findeIndex((item) => item.role_id === id),
					//   1
					// );
					// await this.$http({
					//   url: `/role/remove/${id}`,
					//   method: "post",
					// });
					// this.list.splice(
					//   this.list.findIndex((item) => item.role_id === id),
					//   1
					// );
					await this.roleRemove(id);
					this.$message({
						type: "success",
						message: "删除成功!",
					});
				})
				.catch(() => {
					this.$message({
						type: "info",
						message: "已取消删除",
					});
				});
		},
		async beginRoleFuncConfig(role_id) {
			// 角色功能分配
			this.configFunc.model.role_id = role_id;
			const list = await RoleFuncApi.getRoleFunctions(role_id);
			const roleFuncIds = [];
			list.forEach((func) => roleFuncIds.push(func.func_id));

			let result = [];
			this.funcList
				.filter((func) => func.func_fid === 0)
				.forEach((item) => {
					let node = JSON.parse(JSON.stringify(item));
					node.selected = roleFuncIds.some((func) => func === item.func_id);
					if (!node.func_key) {
						let children = this.funcList.filter(
							(func) => func.func_fid === node.func_id
						);
						if (children.length) {
							node.children = [];
							children.forEach((item2) => {
								let child = JSON.parse(JSON.stringify(item2));
								child.selected = roleFuncIds.some(
									(func) => func === item2.func_id
								);
								node.children.push(child);
							});
						}
					}
					this.configFunc.treeData = result;
					result.push(node);
				});

			this.configFunc.isEdit = true;
		},
		switchChangeHandler(func) {
			if (func.children) {
				func.children.forEach((item) => (item.selected = func.selected));
			} else {
				if (func.func_fid !== 0) {
					let father = this.configFunc.treeData.find(
						(item) => item.func_id === func.func_fid
					);
					father.selected = father.children.some((item) => item.selected);
				}
			}
		},
		async configRoleFunc() {
			let ids = [];
			this.configFunc.treeData.forEach((item) => {
				if (item.selected) {
					ids.push(item.func_id);
					if (item.children) {
						item.children.forEach((item2) => {
							if (item2.selected) ids.push(item2.func_id);
						});
					}
				}
			});
			this.configFunc.model.role_func_ids = ids.join(",");

			await RoleFuncApi.configRoleFunc(this.configFunc.model);

			this.configFunc.isEdit = false;
			this.$message({
				type: "success",
				message: "角色功能配置成功",
			});
		},
	},
	//mapState 里是一个个state里的数据对象 这些对象包装成了 函数的形式来返回数据所以在这里可以当做计算属性
	computed: {
		...mapState("role", { roleList: "list" }),
		...mapState("func", { funcList: "list" }),
	},
	async created() {
		this.funcInit(); //初始化所有功能数据
		this.roleInit(); //初始化所有角色数据
	},
};
</script>

<style scoped lang="stylus">
.el-row
   .cart-name,.cart-plus
      height 120px
      position relative
      display flex
      align-items center
      justify-content center
  .cart-name
    overflow hidden
    font-size 20px
    span
      color 20px
      color #666
    .mask
      border-radius 5px
      position absolute
      top 0
      right 0
      bottom 0
      left 0
      background rgba(0,0,0,.8)
      display flex
      align-items center
      justify-content space-around
      .el-button
        font-size 16px
        color white
        cursor pointer
        &:hover
          text-decoration underline
          color #F56C6C
  .cart-plus
    box-shadow 0 0 2px #FF6A6A!important
    i.el-icon-plus
      color #e67a73
      font-size 26px
      cursor pointer
.el-drawer
	padding 20px!important
	.tree-wrapper
		padding 20px
		.el-tree
			.custom-tree-node
				width 100%
				display flex
				justify-content space-between
				align-items center
				font-size 16px
				color #aaa
  .btn-wraper
    margin-top 100px
</style>
